$(function () {
    layui.use(['layer', 'form', 'laypage'], function(){
        const layer = layui.layer;
        const form = layui.form;
        const laypage = layui.laypage;
        let currentEditId = null;
        let currentPage = 1;
        const pageSize = 10;
        let queryParams = {};

        // 加载学生列表（带分页）
        function loadStudents(page) {
            const params = {
                ...queryParams,
                pageIndex: page - 1,
                pageSize: pageSize
            };

            $.ajax({
                url: "/api/student/getbyPage",
                method: "POST",
                contentType: "application/json",
                data: JSON.stringify(params),
                success: function (res) {
                    if (res.code === 1) {
                        const pageData = res.data;
                        renderTable(pageData.content);
                        renderPagination(pageData.totalElements, pageData.totalPages, page);
                    } else {
                        layer.msg('加载失败: ' + res.msg);
                    }
                },
                error: function(xhr) {
                    layer.msg('加载失败: ' + (xhr.responseJSON?.msg || '未知错误'));
                }
            });
        }

        // 渲染表格
        function renderTable(students) {
            let html = "";
            students.forEach(student => {
                html += `
                <tr>
                    <td>${student.id}</td>
                    <td>${student.name}</td>
                    <td>${student.sex}</td>
                    <td>${student.age}</td>
                    <td>${student.number}</td>
                    <td>
                        <button class="layui-btn layui-btn-sm layui-btn-normal btn-edit" 
                                data-id="${student.id}">编辑</button>
                        <button class="layui-btn layui-btn-sm layui-btn-danger btn-delete" 
                                data-id="${student.id}">删除</button>
                    </td>
                </tr>`;
            });
            $("#studentTb").html(html);
        }

        // 渲染分页
        function renderPagination(total, totalPages, current) {
            laypage.render({
                elem: 'pagination',
                count: total,
                limit: pageSize,
                curr: current,
                layout: ['count', 'prev', 'page', 'next', 'skip'],
                jump: function(obj, first) {
                    if (!first) {
                        currentPage = obj.curr;
                        loadStudents(currentPage);
                    }
                }
            });
        }

        // 初始化加载
        loadStudents(currentPage);

        // 查询按钮事件
        form.on('submit(search)', function(data) {
            queryParams = {
                data: {
                    name: data.field.name || null,
                    number: data.field.number || null,
                    sex: data.field.sex || null
                }
            };
            currentPage = 1;
            loadStudents(currentPage);
            return false;
        });

        // 添加按钮点击事件
        $("#btnAdd").click(function() {
            currentEditId = null;
            layer.open({
                type: 1,
                title: '添加学生',
                content: $('#formContainer'),
                area: ['500px', 'auto'],
                success: function() {
                    $('#studentForm')[0].reset();
                    form.render();
                }
            });
        });

        // 删除操作
        $(document).on('click', '.btn-delete', function() {
            const id = $(this).data('id');
            layer.confirm('确定删除该学生吗？', function(index) {
                $.ajax({
                    url: `/api/student/delete/${id}`,
                    method: "DELETE",
                    success: function() {
                        loadStudents(currentPage);
                        layer.msg('删除成功');
                    },
                    error: function(xhr) {
                        layer.msg('删除失败: ' + (xhr.responseJSON?.msg || '未知错误'));
                    }
                });
                layer.close(index);
            });
        });

        // 编辑操作
        $(document).on('click', '.btn-edit', function() {
            currentEditId = $(this).data('id');
            const row = $(this).closest('tr');
            const student = {
                id: currentEditId,
                name: row.find('td:eq(1)').text(),
                sex: row.find('td:eq(2)').text(),
                age: parseInt(row.find('td:eq(3)').text()),
                number: row.find('td:eq(4)').text()
            };

            layer.open({
                type: 1,
                title: '编辑学生信息',
                content: $('#formContainer'),
                area: ['500px', 'auto'],
                success: function() {
                    $('input[name="name"]').val(student.name);
                    $('input[name="number"]').val(student.number);
                    $('select[name="sex"]').val(student.sex);
                    $('input[name="age"]').val(student.age);
                    form.render();
                }
            });
        });

        // 表单提交
        form.on('submit(student-add)', function(data) {
            const url = currentEditId ? '/api/student/update' : '/api/student/add';
            const method = currentEditId ? 'PUT' : 'POST';

            if (currentEditId) {
                data.field.id = currentEditId;
            }
            data.field.age = parseInt(data.field.age);

            $.ajax({
                url: url,
                method: method,
                contentType: "application/json",
                data: JSON.stringify(data.field),
                success: function(res) {
                    layer.closeAll();
                    loadStudents(currentPage);
                    layer.msg(currentEditId ? '修改成功' : '添加成功');
                },
                error: function(xhr) {
                    layer.msg('操作失败: ' + (xhr.responseJSON?.msg || '未知错误'));
                }
            });
            return false;
        });
    });
});